﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Nancy.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Schema;

namespace EasyClassWEBAPI.Utils
{
    public class TokenInfo
    {
        public string Account { get; set; }
        public string Password { get; set; }
        public TokenInfo(string Account,string Password)
        {
            this.Account = Account;
            this.Password = Password;
        }
    }
    public class TokenTools
    {
        public static string SecretKey = "ZSLSQXMX";//服务器端加密秘钥
        private static JavaScriptSerializer EasyClassJson = new JavaScriptSerializer();
        public static string TokenEncoder(TokenInfo a)
        {
            Dictionary<string, string> UserInfo = new Dictionary<string, string> { { "Account", a.Account }, { "PassWord", a.Password } };
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(UserInfo, SecretKey);
        }
        public static TokenInfo TokenDecoder(string Token)
        {
            var json = GetTokenJson(Token);
            TokenInfo info = EasyClassJson.Deserialize<TokenInfo>(json);
            return info;
        }
        public static string GetTokenJson(string Token)
        {
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder,algorithm);
            var json = decoder.Decode(Token, SecretKey, verify: true);
            return json;
        }
    }
}
